package com.example.duihua.controller;

import com.example.duihua.entity.User;
import com.example.duihua.service.UserService;
import com.example.duihua.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/debug")
public class DebugController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/create-test-user")
    public ResponseEntity<?> createTestUser() {
        try {
            // 删除已存在的测试用户
            User existingUser = userService.findByUsername("testuser");
            if (existingUser != null) {
                return ResponseEntity.ok(ApiResponse.error("测试用户已存在"));
            }
            
            // 创建新的测试用户
            User testUser = new User();
            testUser.setUsername("testuser");
            testUser.setPassword("123456"); // 这会在 UserService 中被加密
            testUser.setNickname("测试用户");
            testUser.setStatus("OFFLINE");
            
            userService.save(testUser);
            
            return ResponseEntity.ok(ApiResponse.success("测试用户创建成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("创建失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/check-password/{username}/{password}")
    public ResponseEntity<?> checkPassword(@PathVariable String username, @PathVariable String password) {
        try {
            User user = userService.findByUsername(username);
            if (user == null) {
                return ResponseEntity.ok(ApiResponse.error("用户不存在"));
            }
            
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            return ResponseEntity.ok(ApiResponse.success("密码验证结果: " + matches + ", 用户: " + username));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("验证失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/encode-password/{password}")
    public ResponseEntity<?> encodePassword(@PathVariable String password) {
        try {
            String encoded = passwordEncoder.encode(password);
            return ResponseEntity.ok(ApiResponse.success("加密结果: " + encoded));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("加密失败: " + e.getMessage()));
        }
    }
}